<?php

namespace app\common\model;

use think\Model;
use think\Db;

class ArticleClass extends Model {

    protected function initialize() {
        parent::initialize();
    }

    /**
     * 构造三级分类
     * @return type
     */
    public function getNavCatTree() {
        if(!cache('nav_tree')){
            // 取出所有顶级
            $data = Db::name($this->name)->where('parent_id=0')->select();
            if ($data) {
                // 循环每个顶级取二级
                foreach ($data as $k => $v) {
                    $data[$k]['children'] = Db::name($this->name)->where('parent_id=' . $v['article_class_id'])->select();
                    // 循环每个二级取三级
                    if($data[$k]['children']){
                        foreach ($data[$k]['children'] as $k1 => $v1) {
                            $data[$k]['children'][$k1]['children'] = Db::name($this->name)->where('parent_id=' . $v1['article_class_id'])->select();
                        }
                    }
                }
            }
            cache('nav_tree',$data);
            return $data;
        }else{
            return cache('nav_tree');
        }
    }
    
    /**
     * 查询该分类下的文章数量
     */
    public function getArticleSum ($article_class_id) {
        return Db::name('Article')->where('article_class_id='.$article_class_id)->count();
    }
    
    /**
     * 查询该分类下的分类数量
     */
    public function getClassSum ($article_class_id) {
        return Db::name('ArticleClass')->where('parent_id='.$article_class_id)->count();
    }
    
    
    
    //获取分类层级
    public function Tree() {
        return $this->_reSort(Db::name($this->name)->select());
    }

    // 递归对有的分类进行重新排序
    private function _reSort($data, $parent_id = 0, $level = 0) {
        static $ret = array();
        foreach ($data as $k => $v) {
            if ($v['parent_id'] == $parent_id) {
                // 把level值放到这个分类里，这样就可以知道这个分类是第几级的
                $v['level'] = $level;
                $ret[] = $v;
                // 再找这个分类的子分类
                $this->_reSort($data, $v['article_class_id'], $level + 1);
            }
        }
        return $ret;
    }
    

}
